package com.physics.mps.module.compute;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.physics.mps.common.exception.BusinessException;
import com.physics.mps.common.util.AssertUtil;
import com.physics.mps.common.util.OkHttpUtil;
import com.physics.mps.entity.dto.SubTaskEntity;
import com.physics.mps.entity.dto.TaskComputeResultEntity;
import com.physics.mps.entity.enums.CodeEnum;
import com.physics.mps.mapper.SubTaskMapper;
import com.physics.mps.mapper.TaskComputeResultMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author mcsoft
 * @date 2023/10/11 16:26
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskComputeResultServiceImpl extends ServiceImpl<TaskComputeResultMapper, TaskComputeResultEntity> implements TaskComputeResultService {

    private final SubTaskMapper subTaskMapper;

    @Override
    public byte[] getResultPic(String id) throws IOException {
        TaskComputeResultEntity byId = this.getById(id);
        AssertUtil.isNull(byId, CodeEnum.SUB_TASK_NOT_EXIST);
        AssertUtil.isFalse(CodeEnum.RESULT_FILE_NOT_EXIST, FileUtil.exist(byId.getPicPath()));
        String picPath = byId.getPicPath();
        AssertUtil.isFalse(CodeEnum.COMPUTE_PIC_FILE_NOT_EXIST, FileUtil.exist(picPath));
        Path path = Paths.get(picPath);
        return Files.readAllBytes(path);
    }

    @Override
    public void downloadFolder(HttpServletResponse response, String id) {
        SubTaskEntity byId = subTaskMapper.selectById(id);
        try (InputStream inputStream = FileUtil.getInputStream(byId.getTaskComputeResult().getFilePath());
             ServletOutputStream outputStream = response.getOutputStream()) {
            // 设置响应头信息
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String filename = Paths.get(byId.getTaskComputeResult().getFilePath()).getFileName().toString();
            response.setHeader("Content-disposition",
                    "attachment;filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));
            IOUtils.copy(inputStream, outputStream);
            log.info("下载完成:{}", filename);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new BusinessException(CodeEnum.DOWNLOAD_EXCEPTION);
        }
    }

    @Override
    public void downloadFolder(HttpServletResponse response, String id, String path) {
        TaskComputeResultEntity byId = this.getById(id);
        String url = byId.getResultUrl();
        String[] s = byId.getFilePath().split("\\\\");
        String local = path + s[s.length - 1];
        OkHttpUtil.download(url, local);
    }


    @Override
    public String getErrorTaskResult(String id) {
        AssertUtil.isBlank(id, CodeEnum.TASK_ID_IS_BLANK);
        SubTaskEntity subTaskEntity = subTaskMapper.selectById(id);
        AssertUtil.isNull(subTaskEntity, CodeEnum.SUB_TASK_NOT_EXIST);
        String cmdLog = subTaskEntity.getCmdLog();
        String logPath = subTaskEntity.getLogPath();
        // 优先展示cmdLog内容
        if (StrUtil.isNotEmpty(cmdLog)) {
            return cmdLog;
        }
        if (!FileUtil.exist(logPath)) {
            return "";
        }
        return FileUtil.readString(logPath, StandardCharsets.UTF_8);
    }

}
